import { reqUserLogin } from "@/api/axios/userlogin";

// 初始值，页面刷新时，vuex的数据会丢失，可以在localStorage
const initState = JSON.parse(localStorage.getItem("user")) || {
  token: "",
  name: "",
};
export default {
  namespaced: true,
  state: initState,
  actions: {
    // 登录请求函数
    async reqLogin({ commit }, { phone, password }) {
      const result = await reqUserLogin(phone, password);
      // console.log(result);会返回 对象，会有返回一个token
      commit("LOGIN", result);
    },
  },
  mutations: {
    LOGIN(state, user) {
         
      state.name = user.name; //保存到vuex.store.state中
      state.token = user.token; ////保存到vuex.store.state中
     
      localStorage.setItem(
        //保存到本地中
        "user",
        JSON.stringify({ name: user.name, token: user.token })
      );
    // console.log(JSON.parse(localStorage.getItem('user')));
    },
    LOGOUT (state){
        state.name= "",
        state.token = "",
        localStorage.removeItem('user')
    }
  },
};
